package com.wobito.controller.admin;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wobito.common.constants.BaseResponse;
import com.wobito.common.constants.BusinessException;
import com.wobito.common.constants.ErrorCode;
import com.wobito.common.constants.TableDataInfo;
import com.wobito.common.utils.LoginInfoContext;
import com.wobito.common.utils.MD5Utils;
import com.wobito.common.utils.ResultUtils;
import com.wobito.pojo.bean.Manager;
import com.wobito.pojo.bean.Person;
import com.wobito.pojo.dto.user.LoginInfoDTO;
import com.wobito.pojo.dto.user.UserDTO;
import com.wobito.pojo.enums.UserRoleEnum;
import com.wobito.pojo.vo.user.AddUserVO;
import com.wobito.pojo.vo.user.UpdatePwdVO;
import com.wobito.pojo.vo.user.UpdateUserVO;
import com.wobito.pojo.vo.user.UserVO;
import com.wobito.service.IManagerService;
import com.wobito.service.IPersonService;
import com.wobito.service.UserService;
import com.wobito.system.aspect.OperLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author Wangbaba
 * @Date 2024/9/2 15:04
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/manage/userManage")
@Api(tags = "用户管理")
public class UserManageController {

    @Autowired
    private UserService userService;
    @Autowired
    private IPersonService personService;
    @Autowired
    private IManagerService managerService;

    @GetMapping("getElor")
    @ApiOperation(value = "查询当前用户角色")
    @OperLog(thing = "查询当前用户角色")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse getElor() {
        LoginInfoDTO loginInfoDTO= LoginInfoContext.getLogin();
        return ResultUtils.success(MD5Utils.getMD5Hash(String.valueOf(loginInfoDTO.getRoleId())));
    }

    @GetMapping()
    @ApiOperation(value = "根据条件查询用户")
    @OperLog(thing = "根据条件查询用户")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse getUserList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(value = "queryName", required = false) String queryName,
                                    @RequestParam(value = "role", required = false) Integer role) {
        TableDataInfo dataInfo = new TableDataInfo();
        PageHelper.startPage(pageNum, pageSize);
        List<UserDTO> userList = userService.selectUserList(new UserVO(queryName,role));
        dataInfo.setRows(userList);
        dataInfo.setTotal(new PageInfo(userList).getTotal());
        return ResultUtils.success(dataInfo);
    }

    @PutMapping()
    @ApiOperation(value = "添加用户")
    @OperLog(thing = "添加用户")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse addUser(@Valid @RequestBody AddUserVO addUserVO) {
        if (addUserVO.getRole().equals(UserRoleEnum.REGION_ADMIN.getCode())&&addUserVO.getAreaId()==null){
            throw new BusinessException(ErrorCode.FORBIDDEN,"区域管理员必须指定区域!");
        }
        return ResultUtils.success(userService.insertUser(addUserVO));
    }

    @PutMapping("/bindingPerson/{userId}")
    @ApiOperation(value = "绑定借阅人")
    @OperLog(thing = "绑定借阅人")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse bindingPerson(@PathVariable("userId")Long userId,@RequestParam("personId")Long personId){
        Person person=personService.getById(personId);
        if (ObjUtil.isEmpty(person)){
            throw new BusinessException(ErrorCode.FORBIDDEN,"该借阅人不存在!");
        }
        Manager manager=managerService.getOne(new LambdaQueryWrapper<Manager>().eq(Manager::getPersonId,personId));
        if (ObjectUtil.isNotEmpty(manager)){
            throw new BusinessException(ErrorCode.FORBIDDEN,"该用户已绑定借阅人!");
        }
        return ResultUtils.success(managerService.save(new Manager(userId,personId)));
    }

    @PostMapping()
    @ApiOperation(value = "修改用户")
    @OperLog(thing = "修改用户")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse updateUser(@Valid @RequestBody UpdateUserVO updateUserVO) {
        return ResultUtils.success(userService.updateUser(updateUserVO));
    }

    @PostMapping("/updatePwd")
    @ApiOperation(value = "修改个人密码")
    @OperLog(thing = "修改个人密码")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse updatePwd(@Valid @RequestBody UpdatePwdVO updatePwdVO){
        return ResultUtils.success(userService.updatePwd(updatePwdVO));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户")
    @OperLog(thing = "删除用户")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse delUser(@PathVariable("id") Long id) {
        return ResultUtils.success(userService.removeById(id));
    }

    @DeleteMapping("/unBindingPerson/{userId}")
    @ApiOperation(value = "解绑借阅人")
    @OperLog(thing = "解绑借阅人")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN','NOMAL_ADMIN')")
    public BaseResponse unBindingPerson(@PathVariable("userId")Long userId,@RequestParam("personId")Long personId){
        Person person=personService.getById(personId);
        if (ObjUtil.isEmpty(person)){
            throw new BusinessException(ErrorCode.FORBIDDEN,"该借阅人不存在!");
        }
        Manager manager=managerService.getOne(new LambdaQueryWrapper<Manager>().eq(Manager::getPersonId,personId));
        if (ObjectUtil.isEmpty(manager)){
            throw new BusinessException(ErrorCode.FORBIDDEN,"该用户未绑定借阅人!");
        }
        return ResultUtils.success(managerService.remove(new LambdaQueryWrapper<Manager>().eq(Manager::getUserId,userId)));
    }
}
